#!/usr/bin/env ruby
require 'gtk2'
require 'fileutils'
require 'digest/md5'
require 'open3'

# Parse command line argument.
filename = ARGV.shift
unless filename
    $stderr.puts "usage: #{$0} filename"
    exit 1
end

# Creates the main window.
window = Gtk::Window.new

# You should always remember to connect the delete_event signal
# to the main window. This is very important for proper intuitive
# behavior.
window.signal_connect("delete_event") do
    Gtk::main_quit
    false
end
window.border_width = 10

filename_digest = Digest::MD5.hexdigest(filename)
tmp_dir = "/tmp/metate/#{filename_digest}"
FileUtils.rm_rf tmp_dir
FileUtils.mkdir_p tmp_dir

Gtk::quit_add(0) {
  FileUtils.rm_rf tmp_dir
}

# first lets extract attachments
FileUtils.mkdir_p "#{tmp_dir}/attachments"
attachment_id = 1
begin
  stdin, stdout, stderr = Open3.popen3("export PREVIOUS_PWD=$PWD; cd #{tmp_dir}/attachments/; mkvextract attachments \"$PREVIOUS_PWD/#{filename}\" #{attachment_id}; cd -")
  output_lines = stdout.readlines
  #STDOUT.puts stdout.readlines
  #STDERR.puts stderr.readlines
  attachment_id += 1
end until !(!output_lines.nil? and !output_lines[1].nil? and output_lines[1].start_with? 'The attachment')


# We create a vertical box (vbox) to pack the horizontal boxes into (created by make_box).
# This allows us to stack the horizontal boxes filled with buttons one
# on top of the other in this vbox.
vbox = Gtk::VBox.new(false, 0)


filename_hbox = Gtk::HBox.new(false, 0)
filename_label = Gtk::Label.new(filename)
filename_hbox.pack_start(filename_label, true, false, 0)
vbox.pack_start(filename_hbox, true, false, 0)
filename_separator = Gtk::HSeparator.new
vbox.pack_start(filename_separator, false, true, 5)

attachments_hbox = Gtk::HBox.new
attachments_label = Gtk::Label.new('attachments')
attachments_hbox.pack_start(attachments_label, true, false, 0)
vbox.pack_start(attachments_hbox, true, false, 0)
attachments_separator = Gtk::HSeparator.new
vbox.pack_start(attachments_separator, false, true, 5)


Gtk::IconSize.register('attachment', 100, 100)
size = Gtk::IconSize.from_name('attachment')
Dir.foreach("#{tmp_dir}/attachments") { |attachment_filename|
  if attachment_filename != '.' and attachment_filename != '..' then
#image
image_hbox = Gtk::HBox.new
image = Gtk::Image.new(attachment_filename, size)
image_hbox.pack_start(image, true, false, 0)
vbox.pack_start(image_hbox, true, false, 0)
  end
}

# Creates a new box, and packs a 'quit' button to it.
# This button can be used to terminate the program, exactly like the window
# close cross.
quit_hbox = Gtk::HBox.new(false, 0)
quit_button = Gtk::Button.new("Quit")
quit_button.signal_connect("clicked") do
  Gtk::main_quit
end 

quit_hbox.pack_start(quit_button, true, false, 0)
vbox.pack_start(quit_hbox, true, false, 0)
window.add(vbox)

# Display all widgets.
window.show_all

# As usual, we finish by entering the main loop, with Gtk.main.
Gtk::main
